


import { ALL, Config, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, Init, Inject } from '@midwayjs/core';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import { CoolCommException, CoolUrlTagData, TagTypes } from '@cool-midway/core';
import { Utils } from '../../../comm/utils';
import { ProviderTeamService } from '../service/team';

/**
 * 用户
 */
@Middleware()
export class ProviderMiddleware implements IMiddleware<Context, NextFunction> {
    @Config(ALL)
    coolConfig;

    @Inject()
    coolUrlTagData: CoolUrlTagData;

    @Inject()
    providerTeamService: ProviderTeamService

    @Config('module.provider.jwt')
    jwtConfig;

    ignoreUrls: string[] = [];

    @Config('koa.globalPrefix')
    prefix;

    @Inject()
    utils: Utils;

    @Init()
    async init() {
        this.ignoreUrls = this.coolUrlTagData.byKey(TagTypes.IGNORE_TOKEN, 'provider');
    }

    resolve() {
        return async (ctx: Context, next: NextFunction) => {
            let { url } = ctx;
            url = url.replace(this.prefix, '').split('?')[0];
            if (_.startsWith(url, '/provider/')) {
                const token = ctx.get('Authorization');
                try {
                    ctx.provider = jwt.verify(token, this.jwtConfig.secret);
                    if (ctx.provider.isRefresh) {
                        throw new CoolCommException('登录失效~');
                    }

                    const team = await this.providerTeamService.getTeamByProviderId(ctx.provider.id);
                    if (!team) {
                        throw new CoolCommException('无权限~');
                    }

                    ctx.team = team;
                } catch (error) { }
                // 使用matchUrl方法来检查URL是否应该被忽略
                const isIgnored = this.ignoreUrls.some(pattern =>
                    this.utils.matchUrl(pattern, url)
                );
                if (isIgnored) {
                    await next();
                    return;
                } else {
                    if (!ctx.provider) {
                        ctx.status = 401;
                        throw new CoolCommException('登录失效~');
                    }
                }
            }
            await next();
        };
    }
}
